<template>
  <div id="configureClassifiAddEdit">
    <el-dialog
      class="about-set"
      :title="showTitle"
      :visible.sync="dialogAddData.isShow"
      width="420px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类属性" prop="labelProperty">
            <el-select
              v-model="ruleForm.labelProperty"
              placeholder=""
              :disabled="isEdit"
            >
              <el-option
                v-for="item in labelPropeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类名称" prop="labelCategoryId">
            <el-select
              filterable
              clearable
              v-model="ruleForm.labelCategoryId"
              placeholder=""
            >
              <el-option
                v-for="item in classNameList"
                :key="item.id"
                :label="item.labelCategoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签名称" prop="labelName">
            <el-input
              clearable
              v-model.trim="ruleForm.labelName"
              :maxlength="nameLength"
              show-word-limit
              :disabled="isEdit"
            ></el-input>
          </el-form-item>
          <el-form-item label="启用状态" prop="enabled">
            <el-radio-group v-model="ruleForm.enabled">
              <el-radio
                v-for="item in enabledList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              clearable
              v-model.trim="ruleForm.remark"
              maxlength="15"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getClasses } from '@/api/contentTags/configureTag' // 接口
import {
  postAddLable,
  checkName,
  editLable
} from '@/api/contentTags/configureTation' // 接口
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { validateSpecial } from '@utils/validate'
export default {
  name: 'DialogAddEdit',
  msg: '标签配置-新增/编辑弹窗',
  props: ['dialogAddData', 'nameLength'],
  data() {
    var category = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择分类名称'))
      } else {
        callback()
        if (this.ruleForm.labelName) {
          this.$refs.ruleForm.validateField('labelName')
        }
      }
    }
    //校验标签名称是否重复
    var valitName = (rule, value, callback) => {
      /*if (!validateSpecial(value)) {
        callback(new Error('名称不能包含特殊字符'))
      }*/
      if (!this.ruleForm.labelCategoryId) {
        //没有选择分类，不做重复校验
        callback()
        return
      }
      if (this.isEdit) {
        //编辑，不做校验
        callback()
        return
      }
      let obj = {
        name: value,
        labelCategoryId: this.ruleForm.labelCategoryId,
        labelProperty: this.ruleForm.labelProperty
      }
      checkName(
        obj,
        (response) => {
          if (response) {
            //true-有重复
            callback(new Error('标签名称已使用'))
          } else {
            //false-无重复
            callback()
          }
        },
        (res) => {
          callback(new Error('校验失败'))
        }
      )
    }
    return {
      loading: false,
      isEdit: false, //是否为编辑，默认新增
      id: null, //编辑时，标签id
      showTitle: '添加标签', //
      ruleForm: {
        labelCategoryId: '', // 分类名称
        labelProperty: '', // 分类属性
        labelName: '', // 标签名称
        enabled: null, // 分类状态
        remark: '' //备注
      },
      labelPropeList: [], //分类属性
      classNameList: [], // 标签属性
      enabledList: [], // 状态
      defaultClassifiName: {
        //默认值
        labelCategoryName: '-- 请选择标签分类 --',
        id: ''
      },
      rules: {
        labelCategoryId: {
          validator: category,
          trigger: 'change'
        },
        labelProperty: {
          required: true,
          message: '请选择分类属性',
          trigger: 'blur'
        },
        labelName: [
          {
            required: true,
            message: '请输入标签名称',
            trigger: 'blur'
          },
          { validator: valitName, trigger: 'blur' }
        ],
        enabled: { required: true, message: '请选择分类状态', trigger: 'blur' }
      }
    }
  },

  watch: {
    'ruleForm.labelProperty': {
      //分类属性
      handler(newVal, oldVal) {
        if (newVal) {
          if (!this.isEdit) {
            //新增
            this.classNameList = [this.defaultClassifiName]
            this.ruleForm.labelCategoryId = ''
          }
          this.getClassList(newVal)
        }
      },
      deep: true
    }
  },
  mounted() {
    this.getStatusList()
    if (this.dialogAddData.type === 'edit') {
      this.showTitle = '编辑标签'
      this.isEdit = true
      this.getFormData()
    }
  },
  methods: {
    async getStatusList() {
      // 分类属性
      let data3 = await sysNormalDisable('sys_labels_attribute')
      this.labelPropeList = this.labelPropeList.concat(data3)
      // 分类状态
      let data2 = await sysNormalDisable('sys_labels_statu')
      this.enabledList = this.enabledList.concat(data2)
      if (this.isEdit) return
      //设置默认数据
      this.setDefaultValue()
    },
    /*设置默认数据*/
    setDefaultValue() {
      this.ruleForm.labelProperty = this.labelPropeList[0].dictValue
      this.ruleForm.enabled = this.enabledList[0].dictValue
    },
    /*编辑-数据回填*/
    getFormData() {
      let {
        labelProperty,
        labelCategoryId,
        labelName,
        enabled,
        remark,
        id
      } = this.dialogAddData.params
      this.ruleForm = {
        labelProperty,
        labelCategoryId: labelCategoryId.toString(),
        labelName,
        enabled: enabled.toString(),
        remark
      }
      this.id = id
    },
    /*获取选择分类列表*/
    getClassList(id) {
      let obj = {
        labelCategoryProperty: id
      }
      getClasses(
        obj,
        (response) => {
          this.classNameList = [this.defaultClassifiName, ...response]
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /* 确认提交 */
    confirmLabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            //编辑
            let { enabled, labelCategoryId, remark } = this.ruleForm
            let obj = { enabled, labelCategoryId, remark }
            obj.enabled = eval(obj.enabled)
            editLable(
              obj,
              this.id,
              (response) => {
                this.loading = false
                this.$emit('refresh')
                this.$message.success('操作成功')
                this.cancelLabel()
              },
              (response) => {
                this.loading = false
                this.$message.warning(
                  this.showTitle + '失败，' + response.message
                )
              }
            )
          } else {
            //新增
            let obj = { ...this.ruleForm }
            obj.enabled = eval(obj.enabled)
            postAddLable(
              obj,
              (response) => {
                this.loading = false
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.loading = false
                this.$message.warning(
                  this.showTitle + '失败，' + response.message
                )
              }
            )
          }
        } else {
          return false
        }
      })
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogAddData.isShow = false
      this.dialogAddData.type = ''
      this.dialogAddData.params = {}
    }
  }
}
</script>

<style lang="less">
#configureClassifiAddEdit {
  .el-input--suffix .el-input__inner {
    padding-right: 70px;
  }
}
</style>
